﻿using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using SlamCms.Common;

namespace SlamCms.Web.Sitemaps
{
	public class BreadcrumbHtmlHelper : IHtmlString
	{
		private readonly SitemapHtmlHelper _sitemapHtmlHelper;
		private bool _includeCurrentNode;
		private string _template;
		private string _class;
		private string _separator = "<span>&gt;</span>";
		private string _currentTitle;

		public BreadcrumbHtmlHelper(SitemapHtmlHelper sitemapHtmlHelper)
		{
			_sitemapHtmlHelper = sitemapHtmlHelper;
		}

		public SitemapHtmlHelper Sitemap
		{
			get
			{
				return _sitemapHtmlHelper;
			}
		}

		public BreadcrumbHtmlHelper AddClass(string @class)
		{
			_class = @class;
			return this;
		}

		public BreadcrumbHtmlHelper IncludeCurrent()
		{
			_includeCurrentNode = true;
			return this;
		}

		public BreadcrumbHtmlHelper UseTemplate(string templateName)
		{
			_template = templateName;
			return this;
		}

		public BreadcrumbHtmlHelper UseSeparator(string separator)
		{
			_separator = separator;
			return this;
		}

		public BreadcrumbHtmlHelper WithCurrent(string title)
		{
			_currentTitle = title;
			return this;
		}

		public string ToHtmlString()
		{
			var breadcrumbNodes = _sitemapHtmlHelper.CurrentNode.GetBreadcrumb(_includeCurrentNode).ToList();

			if (!_currentTitle.IsNullOrEmpty())
			{
				breadcrumbNodes.Add(new SitemapNode()
				{
					Title = _currentTitle 
				});
			}

			var breadcrumbModel = new Breadcrumb(_sitemapHtmlHelper);
			breadcrumbModel.ClassName = _class;
			breadcrumbModel.Separator = _separator;
			breadcrumbModel.IncludeCurrent = _includeCurrentNode;
			breadcrumbModel.Nodes = breadcrumbNodes;
			return _sitemapHtmlHelper.Html.HtmlHelperForModel(breadcrumbModel).DisplayForModel(_template ?? "Breadcrumb").ToHtmlString();
		}
	}
}
